﻿using System;
using Kratos.Framework.Extensions;
using Microsoft.Practices.Unity;

namespace Kratos.Framework.Repositories
{
    public class RepositoryResolver : IRepositoryResolver
    {
        private readonly IUnityContainer _container;

        public RepositoryResolver(IUnityContainer container)
        {
            _container = container;
        }

        public IRepository<T> GetRepository<T>() where T : class
        {
            Type repositoryType = typeof(IRepository<>).MakeGenericType(typeof(T));
            var repository = _container.Resolve(repositoryType) as IRepository<T>;
            if (repository == null)
            {
                throw new ApplicationException("Could not find IRepository<{0}> in Unity".With(typeof(T).Name));
            }
            return repository;
        }

        public void Release(object instance)
        {
            _container.Teardown(instance);
        }
    }
}
